"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 二级分区
Case Name   : range_range二级分区表:并发(同一分区)insert
Create At   : 2022/2/22
Owner       : @daiguatutu
Description :
    1.修改参数值lockwait_timeout=5s和partition_lock_upgrade_timeout=5
    2.创建表和表空间，并插入数据
    3.事务1-开启事务插入数据,等事务2执行结束提交
    4.事务2-对事务一的同一张表进行共享/冲突操作
    5.清理环境
Expect      :
    1.修改成功
    2.成功
    3.成功
    4.前三条成功，最后一条合理报错
    5.清理成功
History     :
"""
import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Subpartition(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.t_name = 't_subpartition_0303'
        self.ts_name = 'ts_subpartition_0303'
        self.default_value1 = self.common.show_param('lockwait_timeout')
        self.default_value2 = self.common.show_param(
            'partition_lock_upgrade_timeout')

    def test_subpartition(self):
        step1_text = '-----step1:修改以下参数值 expect:修改成功-----'
        self.log.info(step1_text)
        param_value = ['lockwait_timeout=5s',
                       'partition_lock_upgrade_timeout=5']
        for value in param_value:
            msg = self.pri_sh.execute_gsguc('reload',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f'{value}')
            self.assertTrue(msg, '执行失败:' + step1_text)

        step2_text = '-----step2:创建表和表空间，并插入数据 expect:成功-----'
        create_sql = f"drop table if exists {self.t_name};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative location " \
            f"'{self.ts_name}';" \
            f"create table if not exists {self.t_name}(" \
            f"col_1 int ,col_2 int ,col_3 varchar2 ( 30 ) ," \
            f"col_4 int)tablespace {self.ts_name} " \
            f"partition by range (col_1) subpartition by range (col_2) " \
            f"( partition p_range_1 values less than(10) " \
            f"  ( subpartition p_range_1_1 values less than(50)," \
            f"    subpartition p_range_1_2 values less than(maxvalue)), " \
            f"  partition p_range_2 values less than(80) " \
            f"  ( subpartition p_range_2_1 values less than(50), " \
            f"    subpartition p_range_2_2 values less than(maxvalue)) " \
            f") enable row movement; " \
            f"insert into {self.t_name} values (generate_series(0, 79)," \
            f"generate_series(0, 79),generate_series(0, 79));"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + step2_text)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + step2_text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg,
                      '执行失败:' + step2_text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, msg,
                      '执行失败:' + step2_text)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg,
                      '执行失败:' + step2_text)

        threads = []
        step3_text = '-----step3:事务1-开启事务插入数据,等事务2执行结束提交 expect:成功-----'
        self.log.info(step3_text)
        session1_sql = f'begin;' \
            f'insert into {self.t_name} values (generate_series(0, 19),' \
            f'generate_series(0, 1000),generate_series(0, 99));' \
            f'select pg_sleep(40);' \
            f'commit;'
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(session1_sql,))
        threads.append(session1)

        step4_text = '-----step4:事务2-对事务一的同一张表进行共享/冲突操作 ' \
                     'expect:前三条成功，最后一条合理报错-----'
        self.log.info(step4_text)
        session2_sql = f'select pg_sleep(5);' \
            f'select * from {self.t_name} ' \
            f'subpartition (p_range_1_2) ;' \
            f'update {self.t_name} set col_2 = 8 where col_2=4;' \
            f'delete {self.t_name} where col_2=5;' \
            f'alter table {self.t_name} truncate subpartition p_range_1_2;'
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(session2_sql,))
        threads.append(session2)

        self.log.info('-----启动线程-----')
        thread_results = []
        for t in threads:
            t.setDaemon(True)
            t.start()
        for t in threads:
            t.join(60)
            thread_results.append(t.get_result())
            self.log.info(t.get_result())
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, thread_results[0],
                      '执行失败:' + step3_text)
        self.assertIn('0 rows', thread_results[1], '执行失败:' + step4_text)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, thread_results[1],
                      '执行失败:' + step4_text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, thread_results[1],
                      '执行失败:' + step4_text)
        self.assertIn('Lock wait timeout', thread_results[1],
                      '执行失败:' + step4_text)

    def tearDown(self):
        self.log.info('-----step5:清理环境-----')
        text_1 = '-----删除表 expect:成功-----'
        self.log.info(text_1)
        del_cmd = f'drop table if exists {self.t_name};' \
            f'drop tablespace if exists {self.ts_name};'
        msg = self.pri_sh.execut_db_sql(del_cmd)
        self.log.info(msg)

        text_2 = '-----恢复参数默认值 expect:成功-----'
        self.log.info(text_2)
        guc_res1 = self.pri_sh.execute_gsguc('reload',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'lockwait_timeout='
                                             f'{self.default_value1}')
        guc_res2 = self.pri_sh.execute_gsguc('reload',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'partition_lock_upgrade_timeout='
                                             f'{self.default_value2}')

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, msg, '执行失败:' + text_1)
        self.assertTrue(guc_res1, '执行失败:' + text_2)
        self.assertTrue(guc_res2, '执行失败:' + text_2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
